<template>
  <div
    class="file_docx"
    ref="fileDocx"
    v-loading="isLoading"
    element-loading-text="加载中，请耐心等待..."
  ></div>
</template>
<script>
import { renderAsync } from "docx-preview";
import { base64ToURL, isBase64String } from "@/utils/file_preview_format";

export default {
  name: "FileDocx",
  props: {
    src: {},
  },
  data() {
    return {
      isLoading: false,
    };
  },
  mounted() {
    if (this.src) {
      this.previewDocx();
    }
  },
  methods: {
    async previewDocx() {
      this.isLoading = true;
      if (isBase64String(this.src)) {
        const blob = base64ToURL(
          this.src,
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        );
        this.viewFile(blob);
      } else {
        try {
          let response;
          if (this.src instanceof File) {
            // 如果 src 是文件 (File) 对象
            response = await fetch(URL.createObjectURL(this.src));
          } else {
            // 如果 src 是链接地址
            response = await fetch(this.src);
          }
          const blob = await response.blob();
          this.viewFile(blob);
        } catch (e) {
          this.$emit("error", e);
        }
      }
    },
    viewFile(src) {
      renderAsync(src, this.$refs.fileDocx)
        .then(() => {
          this.$emit("succeed");
          this.isLoading = false;
        })
        .catch((e) => {
          this.$emit("error", e);
          this.isLoading = false;
        });
    },
  },
};
</script>
<style scoped lang="scss"></style>